package com.turing.post.cardmanagement.impl;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.cardmanagement.util.AdjustInOutStockOrder;
import com.turing.post.cardmanagement.util.AdjustInOutStockOrderBusiness;
import com.turing.post.cardmanagement.util.AdjustInOutStockOrderDao;
import com.turing.post.cardmanagement.util.AdjustInOutStockOrderDetail;
import com.turing.post.cardmanagement.util.AdjustInOutStockOrderDetailDao;
import com.turing.post.cardmanagement.util.CardManaApplicationException;
import com.turing.post.cardmanagement.util.CardStock;
import com.turing.post.cardmanagement.util.CardStockDao;
import com.turing.post.cardmanagement.util.IssueCardStockDetail;
import com.turing.post.cardmanagement.util.IssueCardStockDetailDao;
import com.turing.post.cardmanagement.util.MakeCardControl;
import com.turing.post.cardmanagement.util.MakeCardControlDao;
import com.turing.post.cardmanagement.util.SaleCardStockDetail;
import com.turing.post.cardmanagement.util.SaleCardStockDetailDao;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOpUserDao;
import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.IssueBranchDao;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.organization.util.OrganApplicationException;
import com.turing.post.organization.util.OrganRespCode;
import com.turing.post.organization.util.SaleBranchDao;
import com.turing.post.organization.util.SysBranch;
import com.turing.post.organization.util.SysBranchDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * 调整单管理业务
 * 
 * @author YangShuo
 * 
 */
@Stateless(mappedName = "cardmanagement.impl.AdjustInOutStockOrderBusinessImpl")
@Remote
@Local
public class AdjustInOutStockOrderBusinessImpl implements
		AdjustInOutStockOrderBusiness {

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao pcpsCommonDaoImpl;

	@EJB(mappedName = "common.impl.SysOpUserDaoImpl")
	private SysOpUserDao SysOpUserDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.CardStockDaoImpl")
	private CardStockDao CardStockDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.AdjustInOutStockOrderDetailDaoImpl")
	private AdjustInOutStockOrderDetailDao AdjustInOutStockOrderDetailDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.AdjustInOutStockOrderDaoImpl")
	private AdjustInOutStockOrderDao AdjustInOutStockOrderDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.IssueCardStockDetailDaoImpl")
	private IssueCardStockDetailDao IssueCardStockDetailDaoImpl;

	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao IssueCompanyDaoImpl;

	@EJB(mappedName = "organization.impl.SysBranchDaoImpl")
	private SysBranchDao SysBranchDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.MakeCardControlDaoImpl")
	private MakeCardControlDao MakeCardControlDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.SaleCardStockDetailDaoImpl")
	private SaleCardStockDetailDao SaleCardStockDetailDaoImpl;

	@EJB(mappedName = "organization.impl.IssueBranchDaoImpl")
	private IssueBranchDao issueBranchDaoImpl;

	@EJB(mappedName = "organization.impl.SaleBranchDaoImpl")
	private SaleBranchDao saleBranchDaoImpl;

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;

	/**
	 * 新增调整单
	 * 
	 * @param AdjustInOutStockOrder
	 * @param AdjustInOutStockOrderDetailList
	 */
	@Override
	public BigInteger newAdjustInOutStockOrderWithDetail(PCPSWebInput input,
			AdjustInOutStockOrder adjustInOutStockOrder,
			List<AdjustInOutStockOrderDetail> detaillist)
			throws PCPSApplicationException {
		// 核对输入信息是否正确,首先根据operno得到sysbranch
		if (input == null || PCPSUtil.isEmpty(input.getOperBranchNo())) {
			throw new CardManaApplicationException(
					CardManaApplicationException.ERRCODE_CATEGORY_APPLICATION,
					"", "登录用户信息未空!");
		}
		String branchName = "";
		String branchNo = input.getOperBranchNo();
		SysBranch sb = SysBranchDaoImpl.getSysBranchByBranchNo(branchNo);
		if (sb.getBranchType().equals(SysBranch.SYSBRANCH_ISSUEBRANCH)) {
			// 发卡商机构
			adjustInOutStockOrder.setIssueBranchNo(branchNo);
			// 机构是制卡机构
			branchName = issueBranchDaoImpl.getIssueBranchByIssueBranchNo(
					branchNo).getIssueBranchName();
		} else if (sb.getBranchType().equals(SysBranch.SYSBRANCH_SALEBRANCH)) {
			// 机构是售卡机构
			adjustInOutStockOrder.setSaleBranchNo(branchNo);
			branchName = saleBranchDaoImpl
					.getSaleBranchBySaleBranchNo(branchNo).getSaleBranchName();
		} else {
			// 传入的机构号有误
			throw new CardManaApplicationException(
					CardManaApplicationException.ERRCODE_CATEGORY_APPLICATION,
					"", "机构号码异常或操作员无此权限。");
		}

		// 备注不可为空
		if (PCPSUtil.isEmpty(adjustInOutStockOrder.getRemark()))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"没有填入调整原因。");

		// 检查trantype是否正确
		boolean b = true;
		if (adjustInOutStockOrder.getTranType().equals(
				AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGE))
			b = false;
		if (adjustInOutStockOrder
				.getTranType()
				.equals(
						AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFIT))
			b = false;
		if (adjustInOutStockOrder.getTranType().equals(
				AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSE))
			b = false;
		if (adjustInOutStockOrder
				.getTranType()
				.equals(
						AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_TRANSPLANT))
			b = false;
		if (b)
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"trantype不合法");

		// 产生主键
		adjustInOutStockOrder.setAdjustInOutStockOrderId(pcpsCommonDaoImpl
				.getUniqueIntegerKey());
		// 单据编号
		adjustInOutStockOrder.setOrderNumber(pcpsCommonDaoImpl.getOrderNumber(
				IssueCompanyDaoImpl.getIssueCompanyByIssueCompanyNo(
						PCPSUtil.getICNoByBranchNo(input.getOperBranchNo()))
						.getTranDate(), input.getOperBranchNo()));
		// 记录status
		adjustInOutStockOrder
				.setStatus(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_STATUS_WAITAUTH);
		// 计入数据库
		adjustInOutStockOrder.setTranTime(pcpsCommonDaoImpl
				.getDatabaseSysTime());
		AdjustInOutStockOrderDaoImpl
				.insertAdjustInOutStockOrder(adjustInOutStockOrder);

		// 将list中记录计入明细
		this.insertAdjustInOutStockOrderDetailLis(branchName, branchNo,
				detaillist, adjustInOutStockOrder);

		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(input, SysOperLog.operType_Add,
				"新增调整单", "AdjustInOutStockOrderId:"
						+ adjustInOutStockOrder.getAdjustInOutStockOrderId());
		return adjustInOutStockOrder.getAdjustInOutStockOrderId();
	}

	/**
	 * 调整单审核 调整单ID 审核人 备注 是否通过true通过false不通过
	 * 
	 * @param SaleCompany
	 */
	@Override
	public void authAdjustInOutStockOrderStatus(PCPSWebInput webInput,
			BigInteger AdjustInOutStockOrderID, BigInteger operId,
			String remark, boolean ispass) throws PCPSApplicationException {
		// 根据调整单ID取得调整单对象和详细列表
		AdjustInOutStockOrder aiso = AdjustInOutStockOrderDaoImpl
				.getAdjustInOutStockOrderByAdjustInOutStockOrderId(AdjustInOutStockOrderID);
		// 根据AdjustInOutStockOrderID取得调整明细
		List<AdjustInOutStockOrderDetail> adsodlist = AdjustInOutStockOrderDetailDaoImpl
				.getAdjustInOutStockOrderDetail(AdjustInOutStockOrderID);
		// 取得审核人所属机构与调整单机构作对比
		String sysbranch = aiso.getIssueBranchNo() == null ? aiso
				.getSaleBranchNo() : aiso.getIssueBranchNo();
		String operbranch = SysOpUserDaoImpl.getSysOpUserByOperId(operId)
				.getOperBranchNo();
		if (!sysbranch.equals(operbranch))
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"审核人不属于此机构!请合理分配角色!");
		if (aiso.getOperId().compareTo(operId) == 0)
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"审核人不能是申请人!请合理分配角色!");
		aiso.setAuthOperId(operId);
		aiso.setAuthTime(pcpsCommonDaoImpl.getDatabaseSysTime());
		aiso.setRemark(aiso.getRemark() + "--" + remark);
		if (ispass) {
			// 审核通过，修改状态为通过，记录出入库明细
			aiso
					.setStatus(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_STATUS_PASS);
			AdjustInOutStockOrderDaoImpl.updateAdjustInOutStockOrder(aiso);

			// 记录出入库明细，在记录前验证卡号段状态
			AdjustInOutStockOrderDetail aisod = null;
			HashMap<String, Integer> countMp = null;
			boolean b = false;// 用来标志是调整还是调整取消，在for循环中赋值
			for (int i = 0; i < adsodlist.size(); i++) {
				aisod = adsodlist.get(i);
				// 如果是调整，按照正常状态取卡信息
				if (aiso
						.getTranType()
						.equals(
								AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGE)
						|| aiso
								.getTranType()
								.equals(
										AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFITCANCEL)
						|| aiso
								.getTranType()
								.equals(
										AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSE)) {
					countMp = CardStockDaoImpl
							.getCardStockCountBySysbranchnoNoAndStatusAndCredseqno(
									aisod.getCardStartSeqNo(), aisod
											.getCardEndSeqNo(),
									CardStock.CARDSTOCK_STATUS_NORMAL,
									sysbranch);
					if (countMp.get(CardStock.CARDSTOCK_STATUS_NORMAL)
							.intValue() != aisod.getOrderCount().intValue()) {
						if (countMp.size() <= 1) {
							throw new CardManaApplicationException(
									PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
									"", "库存中不存在卡序号段"
											+ aisod.getCardStartSeqNo() + "至"
											+ aisod.getCardEndSeqNo() + "的卡!");
						} else {
							throw new CardManaApplicationException(
									PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
									"", "卡号段状态异常:"
											+ CardStock.getErrorStatus(countMp));

						}
					}
					b = true;
				} else {
					// 调整取消，按照卡损坏丢失状态检查
					countMp = CardStockDaoImpl
							.getCardStockCountBySysbranchnoNoAndStatusAndCredseqno(
									aisod.getCardStartSeqNo(), aisod
											.getCardEndSeqNo(),
									CardStock.CARDSTOCK_STATUS_MISSING,
									sysbranch);
					if (countMp.get(CardStock.CARDSTOCK_STATUS_MISSING)
							.intValue() != aisod.getOrderCount().intValue()) {
						if (countMp.size() <= 1) {
							throw new CardManaApplicationException(
									PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
									"", "库存中不存在卡序号段"
											+ aisod.getCardStartSeqNo() + "至"
											+ aisod.getCardEndSeqNo() + "的卡!");
						} else {
							throw new CardManaApplicationException(
									PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
									"", "卡号段状态异常:"
											+ CardStock.getErrorStatus(countMp));

						}
					}
					b = false;
				}
				// 修改卡状态
				if (b) {
					// 调整操作，将卡置为丢失损坏
					CardStockDaoImpl.updateCardStock(aisod.getBatchNo(), aisod
							.getCardStartSeqNo(), aisod.getCardEndSeqNo(),
							CardStock.CARDSTOCK_STATUS_MISSING);
					// 记录一笔出库明细,判断机构类型，自动判断正负，发卡商机构计入发卡商机构出入库明细，销售机构计入销售机构出入库明细。
					if (SysBranchDaoImpl.getSysBranchByBranchNo(operbranch)
							.getBranchType().equals(
									SysBranch.SYSBRANCH_ISSUEBRANCH))
						this.insertIssueCardStockDetailList(
								AdjustInOutStockOrderID, aisod, sysbranch,
								operId, getIssTranTypeByStatus(aiso
										.getTranType()), remark,
								1);

					else
						this.insertSaleCardStockDetailList(
								AdjustInOutStockOrderID, aisod, sysbranch,
								operId, getSaleTranTypeByStatus(aiso
										.getTranType()), remark,
								1);

				} else {
					// 取消调整，将卡置为正常
					CardStockDaoImpl.updateCardStock(aisod.getBatchNo(), aisod
							.getCardStartSeqNo(), aisod.getCardEndSeqNo(),
							CardStock.CARDSTOCK_STATUS_NORMAL);
					// 修改原记录，记录取消流水
					AdjustInOutStockOrderDaoImpl
							.updateAdjustInOutStockOrderCancelID(aiso
									.getCancelAdjustInOutStockOrderId(), aiso
									.getAdjustInOutStockOrderId());
					// 记录一笔入库明细,判断机构类型，自动判断正负，发卡商机构计入发卡商机构出入库明细，销售机构计入销售机构出入库明细。
					if (SysBranchDaoImpl.getSysBranchByBranchNo(operbranch)
							.getBranchType().equals(
									SysBranch.SYSBRANCH_ISSUEBRANCH))
						this.insertIssueCardStockDetailList(
								AdjustInOutStockOrderID, aisod, sysbranch,
								operId, getIssTranTypeByStatus(aiso
										.getTranType()), remark,
								-1);
					else
						this.insertSaleCardStockDetailList(
								AdjustInOutStockOrderID, aisod, sysbranch,
								operId, getSaleTranTypeByStatus(aiso
										.getTranType()), remark,
								-1);

				}
			}

			// 日志记录
			sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
					SysOperLog.operType_Add, "调整单审核通过",
					"AdjustInOutStockOrderId:" + AdjustInOutStockOrderID);
		} else {
			// 审核不通过，状态置为不通过
			aiso
					.setStatus(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_STATUS_NOPASS);
			AdjustInOutStockOrderDaoImpl.updateAdjustInOutStockOrder(aiso);

			// 日志记录
			sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
					SysOperLog.operType_Add, "调整单审核不通过",
					"AdjustInOutStockOrderId:" + AdjustInOutStockOrderID);
		}

	}

//	private Integer getRatByStatus(String status) {
//		int i = 0;
//		if (status
//				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGE))
//			i = -1;
//		else if (status
//				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGECANCEL))
//			i = 1;
//		else if (status
//				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFIT))
//			i = 1;
//		else if (status
//				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFITCANCEL))
//			i = -1;
//		else if (status
//				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSE))
//			i = -1;
//		else if (status
//				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSECANCEL))
//			i = 1;
//		else if (status
//				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_TRANSPLANT))
//			i = 1;
//		else if (status
//				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_TRANSPLANTCANCEL))
//			i = -1;
//		return i;
//	}

	private String getIssTranTypeByStatus(String status) {
		String TranType = null;
		if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGE))
			TranType = IssueCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_LOSE;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGECANCEL))
			TranType = IssueCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_LOSE;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFIT))
			TranType = IssueCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_INVENTORY_PROFIT;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFITCANCEL))
			TranType = IssueCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_INVENTORY_PROFIT;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSE))
			TranType = IssueCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_LOSE;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSECANCEL))
			TranType = IssueCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_LOSE;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_TRANSPLANT))
			TranType = IssueCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_INVENTORY_TRANSPLANT;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_TRANSPLANTCANCEL))
			TranType = IssueCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_INVENTORY_TRANSPLANT;
		return TranType;
	}

	private String getSaleTranTypeByStatus(String status) {
		String TranType = null;
		if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGE))
			TranType = SaleCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_LOSE;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGECANCEL))
			TranType = SaleCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_LOSE;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFIT))
			TranType = SaleCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_INVENTORY_PROFIT;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFITCANCEL))
			TranType = SaleCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_INVENTORY_PROFIT;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSE))
			TranType = SaleCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_LOSE;
		else if (status
				.equals(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSECANCEL))
			TranType = SaleCardStockDetail.ISSUECARDSTOCKDETAIL_TRANTYPE_LOSE;
		return TranType;
	}

	/**
	 * 发卡商机构批量插入出入库明细方法,调整单ID，调整明细对象，机构号，审批人，状态，备注，正负标志
	 * 
	 */
	private void insertIssueCardStockDetailList(
			BigInteger AdjustInOutStockOrderID,
			AdjustInOutStockOrderDetail aisod, String sysbranch,
			BigInteger UserId, String status, String remark, int pn)
			throws PCPSApplicationException {
		IssueCardStockDetail ics = new IssueCardStockDetail();
		MakeCardControl mcc = MakeCardControlDaoImpl
				.getMakeCardControlByBatchNo(aisod.getBatchNo());
		ics.setIoOrderId(AdjustInOutStockOrderID);
		ics.setIssueBranchNo(sysbranch);
		ics.setTranDate(IssueCompanyDaoImpl.getIssueCompanyByIssueCompanyNo(
				PCPSUtil.getICNoByBranchNo(sysbranch)).getTranDate());
		ics.setTrantime(pcpsCommonDaoImpl.getDatabaseSysTime());
		ics.setTranType(status);
		ics.setCardFaceId(mcc.getCardFaceId());
		// ics.setCardClassicId(mcc.getCardClassicId());
		// ics.setCardParValueId(mcc.getCardParValueId());
		ics.setBatchNo(mcc.getBatchNo());
		ics.setCardStartSeqNo(aisod.getCardStartSeqNo());
		ics.setCardEndSeqNo(aisod.getCardEndSeqNo());
		ics.setOrderCount(aisod.getOrderCount() * pn);
		ics.setOperId(UserId);
		ics.setRemark(remark);
		IssueCardStockDetailDaoImpl.insert(ics);
	}

	/**
	 * 销售机构批量插入出入库明细方法,调整单ID，调整明细对象，机构号，审批人，状态，备注，正负标志
	 * 
	 */
	private void insertSaleCardStockDetailList(
			BigInteger AdjustInOutStockOrderID,
			AdjustInOutStockOrderDetail aisod, String sysbranch,
			BigInteger UserId, String status, String remark, int pn)
			throws PCPSApplicationException {

		SaleCardStockDetail ics = new SaleCardStockDetail();
		MakeCardControl mcc = MakeCardControlDaoImpl
				.getMakeCardControlByBatchNo(aisod.getBatchNo());

		ics.setIoOrderId(AdjustInOutStockOrderID);
		ics.setSaleBranchNo(sysbranch);
		ics.setTranDate(IssueCompanyDaoImpl.getIssueCompanyByIssueCompanyNo(
				PCPSUtil.getICNoByBranchNo(sysbranch)).getTranDate());
		ics.setTrantime(pcpsCommonDaoImpl.getDatabaseSysTime());
		ics.setTranType(status);
		ics.setCardFaceId(mcc.getCardFaceId());
		// ics.setCardClassicId(mcc.getCardClassicId());
		// ics.setCardParValueId(mcc.getCardParValueId());
		ics.setBatchNo(mcc.getBatchNo());
		ics.setCardStartSeqNo(aisod.getCardStartSeqNo());
		ics.setCardEndSeqNo(aisod.getCardEndSeqNo());
		ics.setOrderCount(aisod.getOrderCount() * pn);
		ics.setOperId(UserId);
		ics.setRemark(remark);
		SaleCardStockDetailDaoImpl.insert(ics);
	}

	/**
	 * 批量插入调整单明细方法
	 * 
	 */
	private void insertAdjustInOutStockOrderDetailLis(String branchName,
			String sysbranch, List<AdjustInOutStockOrderDetail> detaillist,
			AdjustInOutStockOrder aiod) throws PCPSApplicationException {
		AdjustInOutStockOrderDetail aisod = null;
		int j = 1;
		HashMap<String, String> startseqmap = new HashMap<String, String>();
		HashMap<String, String> endseqmap = new HashMap<String, String>();
		for (int i = 0; i < detaillist.size(); i++) {
			aisod = detaillist.get(i);
			aisod.setOrderItemSeqNo(i);
			aisod.setAdjustInOutStockOrderId(aiod.getAdjustInOutStockOrderId());
			if (PCPSUtil.isEmpty(aisod.getCardStartSeqNo())) {
				throw new CardManaApplicationException(
						CardManaApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", "第" + j + "行起始号为空!");
			}
			if (PCPSUtil.isEmpty(aisod.getCardEndSeqNo())) {
				throw new CardManaApplicationException(
						CardManaApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", "第" + j + "行终止号为空!");
			}
			if (startseqmap.get(aisod.getCardStartSeqNo().trim()) != null) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "第" + j + "行起始号已经重复录入!");
			}
			if (endseqmap.get(aisod.getCardEndSeqNo().trim()) != null) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "第" + j + "行终止号已经重复录入!");
			}

			if (endseqmap.get(aisod.getCardStartSeqNo().trim()) != null) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "第" + j + "行起始号已经重复录入!");
			}
			if (startseqmap.get(aisod.getCardEndSeqNo().trim()) != null) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "第" + j + "行终止号已经重复录入!");
			}
			if (isVoucherNo(aisod.getCardStartSeqNo().trim(), startseqmap)
					.endsWith("error")) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "第" + j + "行起始号已经重复录入!");
			}
			if (isVoucherNo(aisod.getCardEndSeqNo().trim().trim(), startseqmap)
					.endsWith("error")) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "第" + j + "行起始号已经重复录入!");
			}
			if (isVoucherNo(aisod.getCardStartSeqNo().trim(), startseqmap)
					.endsWith("error")) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "第" + j + "行起始号已经重复录入!");
			}
			if (isVoucherNo(aisod.getCardEndSeqNo().trim(), endseqmap)
					.endsWith("error")) {
				throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
						"", "第" + j + "行起始号已经重复录入!");
			}
			startseqmap.put(aisod.getCardStartSeqNo().trim(), aisod
					.getCardEndSeqNo().trim());
			endseqmap.put(aisod.getCardEndSeqNo().trim(), aisod
					.getCardStartSeqNo().trim());

			if (AdjustInOutStockOrderDetailDaoImpl
					.IsCardSeq(aisod.getCardStartSeqNo().trim(), aisod
							.getCardEndSeqNo().trim()) > 0) {
				throw new CardManaApplicationException(
						PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", aisod.getCardStartSeqNo().trim() + "-----"
								+ aisod.getCardEndSeqNo().trim()
								+ "号段中已经创建待审核!请先审核!");
			}

			CardStock cardStock = CardStockDaoImpl
					.getCardStockByCardseqno(aisod.getCardStartSeqNo());
			if (cardStock == null) {
				throw new CardManaApplicationException(
						PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", "起始卡序号不存在!");
			}
			aisod.setStartCardNo(cardStock.getCardNo());
			CardStock endcardStock = CardStockDaoImpl
					.getCardStockByCardseqno(aisod.getCardEndSeqNo());

			if (endcardStock == null) {
				throw new CardManaApplicationException(
						PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", "终止卡序号不存在!");
			}
			aisod.setEndCardNo(endcardStock.getCardNo());
			// 验证号段合法性,如果截取和转化出问题说明号段异常，如果张数不符，也不允许继续
			try {
				if (aisod.getCardEndSeqNo().trim().length() < 18) {
					aisod.setOrderCount((Integer.parseInt(aisod
							.getCardEndSeqNo().substring(6, 12))
							- Integer.parseInt(aisod.getCardStartSeqNo()
									.substring(6, 12)) + 1));
				} else {
					aisod.setOrderCount((Integer.parseInt(aisod
							.getCardEndSeqNo().substring(12, 18))
							- Integer.parseInt(aisod.getCardStartSeqNo()
									.substring(12, 18)) + 1));
				}
			} catch (Exception e) {
				throw new CardManaApplicationException(
						PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", branchName + " 卡号段" + aisod.getCardStartSeqNo()
								+ "到" + aisod.getCardEndSeqNo() + "有误，"
								+ e.getMessage());
			}
			if (!aiod
					.getTranType()
					.equals(
							AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFIT)) {// 报损，丢失
				HashMap<String, Integer> countMp = CardStockDaoImpl
						.getCardStockCountBySysbranchnoNoAndStatusAndCredseqno(
								aisod.getCardStartSeqNo(), aisod
										.getCardEndSeqNo(),
								CardStock.CARDSTOCK_STATUS_NORMAL, sysbranch);
				if (countMp.get(CardStock.CARDSTOCK_STATUS_NORMAL) == null) {
					throw new CardManaApplicationException(
							PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
							"", "库存中不存在卡序号段" + aisod.getCardStartSeqNo() + "至"
									+ aisod.getCardEndSeqNo() + "的卡!或状态不是正常状态!");
				}
				if (aisod.getOrderCount().compareTo(
						countMp.get(CardStock.CARDSTOCK_STATUS_NORMAL)) != 0) {
					if (countMp.size() <= 1) {
						throw new CardManaApplicationException(
								PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
								"", "库存中不存在卡序号段" + aisod.getCardStartSeqNo()
										+ "至" + aisod.getCardEndSeqNo() + "的卡!");
					} else {
						throw new CardManaApplicationException(
								PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
								"", "卡号段状态异常:"
										+ CardStock.getErrorStatus(countMp));

					}
				}
			} else {
				HashMap<String, Integer> countMp = CardStockDaoImpl
						.getCardStockCountBySysbranchnoNoAndStatusAndCredseqno(
								aisod.getCardStartSeqNo(), aisod
										.getCardEndSeqNo(),
								CardStock.CARDSTOCK_STATUS_MISSING, sysbranch);
				if (countMp.get(CardStock.CARDSTOCK_STATUS_MISSING) == null) {
					throw new CardManaApplicationException(
							PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
							"", "库存中不存在卡序号段" + aisod.getCardStartSeqNo() + "至"
									+ aisod.getCardEndSeqNo()
									+ "的卡!或状态不是丢失、损坏、不再制卡等!");
				}
				if (aisod.getOrderCount().compareTo(
						countMp.get(CardStock.CARDSTOCK_STATUS_MISSING)) != 0) {
					if (countMp.size() <= 1) {
						throw new CardManaApplicationException(
								PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
								"", "库存中不存在卡序号段" + aisod.getCardStartSeqNo()
										+ "至" + aisod.getCardEndSeqNo() + "的卡!");
					} else {
						throw new CardManaApplicationException(
								PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
								"", "卡号段状态异常:"
										+ CardStock.getErrorStatus(countMp));

					}
				}
			}
			if (PCPSUtil.isEmpty(aisod.getCardStartSeqNo())
					|| PCPSUtil.isEmpty(aisod.getCardEndSeqNo()))
				throw new CardManaApplicationException(
						PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", "起止卡号不能为空");

			// 截取到Batchno
			if (aisod.getCardStartSeqNo().trim().length() < 18) {
				aisod.setBatchNo(PCPSUtil.getICNoByBranchNo(sysbranch)
						+ aisod.getCardStartSeqNo().substring(0, 6));
			} else {
				aisod.setBatchNo(aisod.getCardStartSeqNo().substring(0, 12));
			}
			// 插入数据
			AdjustInOutStockOrderDetailDaoImpl
					.insertAdjustInOutStockOrderDetail(aisod);
			j++;
		}

	}

	/**
	 * 批量插入取消调整单明细方法
	 * 
	 */
	private void insertCancelAdjustInOutStockOrderDetailList(String sysbranch,
			List<AdjustInOutStockOrderDetail> detaillist, BigInteger aiod)
			throws PCPSApplicationException {
		AdjustInOutStockOrderDetail aisod_e = null;
		for (int i = 0; i < detaillist.size(); i++) {
			aisod_e = detaillist.get(i);

			AdjustInOutStockOrderDetail aisod = new AdjustInOutStockOrderDetail();
			aisod.setCardStartSeqNo(aisod_e.getCardStartSeqNo());
			aisod.setCardEndSeqNo(aisod_e.getCardEndSeqNo());
			aisod.setRemark(aisod_e.getRemark());
			aisod.setStartCardNo(aisod_e.getStartCardNo());
			aisod.setEndCardNo(aisod_e.getEndCardNo());

			aisod.setOrderItemSeqNo(i);
			aisod.setAdjustInOutStockOrderId(aiod);

			// 验证号段合法性,如果截取和转化出问题说明号段异常，如果张数不符，也不允许继续
			try {
				if (aisod.getCardEndSeqNo().trim().length() < 18) {
					aisod.setOrderCount((Integer.parseInt(aisod
							.getCardEndSeqNo().substring(6, 12))
							- Integer.parseInt(aisod.getCardStartSeqNo()
									.substring(6, 12)) + 1));
				} else {
					aisod.setOrderCount((Integer.parseInt(aisod
							.getCardEndSeqNo().substring(12, 18))
							- Integer.parseInt(aisod.getCardStartSeqNo()
									.substring(12, 18)) + 1));
				}
			} catch (Exception e) {
				throw new CardManaApplicationException(
						PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", "卡号段" + aisod.getCardStartSeqNo() + "到"
								+ aisod.getCardEndSeqNo() + "有误，"
								+ e.getMessage());
			}

			HashMap<String, Integer> countMp = CardStockDaoImpl
					.getCardStockCountBySysbranchnoNoAndStatusAndCredseqno(
							aisod.getCardStartSeqNo(), aisod.getCardEndSeqNo(),
							CardStock.CARDSTOCK_STATUS_MISSING, sysbranch);
			if (aisod.getOrderCount().compareTo(
					countMp.get(CardStock.CARDSTOCK_STATUS_MISSING)) != 0) {
				if (countMp.size() <= 1) {
					throw new CardManaApplicationException(
							PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
							"", "库存中不存在卡序号段" + aisod.getCardStartSeqNo() + "至"
									+ aisod.getCardEndSeqNo() + "的卡!");
				} else {
					throw new CardManaApplicationException(
							PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
							"", "卡号段状态异常:" + CardStock.getErrorStatus(countMp));

				}
			}

			if (PCPSUtil.isEmpty(aisod.getCardStartSeqNo())
					|| PCPSUtil.isEmpty(aisod.getCardEndSeqNo()))
				throw new CardManaApplicationException(
						PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION,
						"", "起止卡号不能为空");
			// 截取到Batchno
			if (aisod.getCardStartSeqNo().trim().length() < 18) {
				aisod.setBatchNo(PCPSUtil.getICNoByBranchNo(sysbranch)
						+ aisod.getCardStartSeqNo().substring(0, 6));
			} else {
				aisod.setBatchNo(aisod.getCardStartSeqNo().substring(0, 12));
			}
			// 插入数据
			AdjustInOutStockOrderDetailDaoImpl
					.insertAdjustInOutStockOrderDetail(aisod);
		}

	}

	/**
	 * 取消调整单
	 * 
	 * @param SaleCompany
	 */
	@Override
	public void cancelAdjustInOutStockOrderStatus(PCPSWebInput webInput,
			BigInteger AdjustInOutStockOrderID, BigInteger operno, String remark)
			throws PCPSApplicationException {
		// 先根据ID取到需要取消的调整信息
		AdjustInOutStockOrder aiso = AdjustInOutStockOrderDaoImpl
				.getAdjustInOutStockOrderByAdjustInOutStockOrderId(AdjustInOutStockOrderID);

		if (aiso == null) {
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"调整单不存在!");
		}
		// 比对操作员必须是本人操作
		if (!aiso.getStatus().equals(
				AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_STATUS_PASS)) {
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"只可取消审核通过调整单!");
		}
		if (operno.compareTo(aiso.getOperId()) != 0) {
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"必须由本人取消");
		}
		// 根据AdjustInOutStockOrderID取得调整明细
		List<AdjustInOutStockOrderDetail> adsodlist = AdjustInOutStockOrderDetailDaoImpl
				.getAdjustInOutStockOrderDetail(AdjustInOutStockOrderID);
		// 新建需取消AdjustInOutStockOrder对象
		AdjustInOutStockOrder newaiso = new AdjustInOutStockOrder();// /
		BigInteger adInOutOrderId = pcpsCommonDaoImpl.getUniqueIntegerKey();
		newaiso.setOrderNumber(pcpsCommonDaoImpl.getOrderNumber(
				IssueCompanyDaoImpl.getIssueCompanyByIssueCompanyNo(
						PCPSUtil.getICNoByBranchNo(webInput.getOperBranchNo()))
						.getTranDate(), webInput.getOperBranchNo()));
		newaiso.setAdjustInOutStockOrderId(adInOutOrderId);
		newaiso.setIssueBranchNo(aiso.getIssueBranchNo());
		newaiso.setSaleBranchNo(aiso.getSaleBranchNo());
		newaiso.setTranTime(pcpsCommonDaoImpl.getDatabaseSysTime());
		newaiso
				.setStatus(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_STATUS_WAITAUTH);
		if (aiso.getTranType().equals(
				AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGE))
			newaiso
					.setTranType(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_BREAKAGECANCEL);
		if (aiso
				.getTranType()
				.equals(
						AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFIT))
			newaiso
					.setTranType(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_INVENTORYPROFITCANCEL);
		if (aiso.getTranType().equals(
				AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSE))
			newaiso
					.setTranType(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_LOSECANCEL);
		if (aiso
				.getTranType()
				.equals(
						AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_TRANSPLANT))
			newaiso
					.setTranType(AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_TRANTYPE_TRANSPLANTCANCEL);
		newaiso.setCancelAdjustInOutStockOrderId(aiso
				.getAdjustInOutStockOrderId());
		newaiso.setOperId(aiso.getOperId());
		newaiso.setRemark(remark);

		// 将新记录插入数据库
		AdjustInOutStockOrderDaoImpl.insertAdjustInOutStockOrder(newaiso);
		aiso.setCancelAdjustInOutStockOrderId(adInOutOrderId);

		// 根据取消目标取得是销售机构还是发卡商机构，机构号不为空的就是
		String sysbranch = aiso.getIssueBranchNo() == null ? aiso
				.getSaleBranchNo() : aiso.getIssueBranchNo();
		// 将替换过关联主键的list插入数据库
		this.insertCancelAdjustInOutStockOrderDetailList(sysbranch, adsodlist,
				adInOutOrderId);
		AdjustInOutStockOrderDaoImpl.updateAdjustInOutStockOrderCancelID(
				AdjustInOutStockOrderID, adInOutOrderId);
		
		

		
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Add, "取消调整单", "AdjustInOutStockOrderId:"
						+ AdjustInOutStockOrderID);
	}

	@Override
	public void deleteAdjustInOutStockOrderStatus(PCPSWebInput webInput,
			BigInteger adjustInOutStockOrderId, BigInteger operno, String remark)
			throws PCPSApplicationException {
		// 先根据ID取到需要取消的调整信息
		AdjustInOutStockOrder aiso = AdjustInOutStockOrderDaoImpl
				.getAdjustInOutStockOrderByAdjustInOutStockOrderId(adjustInOutStockOrderId);
		// 比对操作员必须是本人操作
		if (!aiso.getStatus().equals(
				AdjustInOutStockOrder.ADJUSTINOUTSTOCKORDER_STATUS_WAITAUTH)) {
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"只可删除等待审核调整单!");
		}
		if (operno.compareTo(aiso.getOperId()) != 0) {
			throw new CardManaApplicationException(
					PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"必须由创建人删除调整单");
		}

		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Add, "删除调整单", "AdjustInOutStockOrderId:"
						+ adjustInOutStockOrderId);
		// 删除字表
		AdjustInOutStockOrderDetailDaoImpl
				.deleteAdjustInOutStockOrderDetail(adjustInOutStockOrderId);
		// 删除主表
		AdjustInOutStockOrderDaoImpl.deleteAdjustInOutStockOrder(aiso
				.getAdjustInOutStockOrderId());
	}

	/**
	 * 验证号段是否重复
	 */
	@SuppressWarnings("unchecked")
	private String isVoucherNo(String Voucherno, Map map) {
		Iterator ite = map.entrySet().iterator();
		while (ite.hasNext()) {
			Map.Entry<Object, Object> entry = (Entry<Object, Object>) ite
					.next();
			Object key = entry.getKey();
			Object value = entry.getValue();
			BigInteger bigkey = new BigInteger(key.toString());
			BigInteger bigvalue = new BigInteger(value.toString());
			BigInteger bigvoucherno = new BigInteger(Voucherno);
			if (bigvoucherno.intValue() >= bigkey.intValue()
					&& bigvoucherno.intValue() <= bigvalue.intValue())
				return "error";
		}
		return "";
	}
}